﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using BusinessLogicLayer.Manager;
using Objects;
using AutoFix.Base;
using Common;

namespace AutoFix
{
    public partial class edit_profile : BasePage
    {
        #region [Private Members]
        /// <summary>
        /// member that holds the logged in user
        /// </summary>
        private User applicationUser = null;
        #endregion

        #region [BasePage Implementations]
        /// <summary>
        /// Gets or sets a value indicating whether [is login page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is login page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsLoginPage { get { return false; } }

        /// <summary>
        /// Gets or sets a value indicating whether [is anonymous page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is anonymous page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsAnonymousPage { get { return false; } }

        /// <summary>
        /// Page name
        /// </summary>
        protected override string PageName
        {
            get { return "Edit Profile"; }
        }

        /// <summary>
        /// Gets the authorized user types.
        /// </summary>
        protected override List<UserType> AuthorizedUserTypes
        {
            get { return new List<UserType>(new UserType[] { UserType.Admin, UserType.Contributor }); }
        }

        #endregion

        #region [Event Handlers]
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            applicationUser = this.PageSession.ApplicationUser;
            if (!IsPostBack)
            {
                UserManager manager = new UserManager();
                List<User> users = null;
                try
                {
                    users = manager.GetUsers(1);
                    this.txtFirstName.Text = users[0].FirstName;
                    this.txtLastName.Text = users[0].LastName;
                    this.txtEmailAddress.Text = users[0].EmailAddress;
                    this.txtUserName.Text = users[0].UserName;
                    this.txtPassword.Text = users[0].Password;
                    this.txtCity.Text = users[0].City;
                    this.ddlCountry.SelectedValue = users[0].Country;
                    this.txtPhoneNumber.Text = users[0].PhoneNumber;
                    if (users[0].ProfilePictureURL == string.Empty)
                    {
                        this.imgUserImage.ImageUrl = "images/imgDefaultProfile.png";
                    }
                    else
                    {
                        this.imgUserImage.ImageUrl = AppConfiguration.UserProfileImagePath + users[0].ProfilePictureURL;
                    }

                }
                catch (Exception)
                {
                    this.pageActionMessage.InnerText = "Failed to load your information to the page";
                    this.pageActionMessage.Attributes.Add("class", "error-msg");
                }
                finally
                {
                    manager = null;
                }
            }
        }
        /// <summary>
        /// Handles the click event of the update button.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            UserManager manager = new UserManager();
            User user = new User();
            bool success = false;
            string fileName = string.Empty;
            string file = string.Empty;
            try
            {
                user.UserID = applicationUser.UserID;
                user.FirstName = this.txtFirstName.Text.Trim();
                user.LastName = this.txtLastName.Text.Trim();
                user.EmailAddress = this.txtEmailAddress.Text.Trim();
                user.UserName = this.txtUserName.Text.Trim();
                user.Password = this.txtPassword.Text.Trim();
                user.City = this.txtCity.Text.Trim();
                user.Country = this.ddlCountry.SelectedValue;
                user.PhoneNumber = this.txtPhoneNumber.Text.Trim();
                user.UserTypeID = 1;
                user.IsActive = true;

                if (this.fleProfilePicture.HasFile)
                {
                    if (this.fleProfilePicture.PostedFile.ContentType == "image/jpeg")
                    {
                        Guid guid = Guid.NewGuid();
                        fileName = WebConfigurationManager.AppSettings["UserProfileImagePath"] + guid + ".jpg";
                        file = Request.MapPath(WebConfigurationManager.AppSettings["UserProfileImagePath"]) + guid + ".jpg";
                        this.fleProfilePicture.SaveAs(file);
                        user.ProfilePictureURL = fileName;
                    }
                    else
                    {
                        this.pageActionMessage.InnerText = "Invalid image file. Only jpg format is allowed";
                        this.pageActionMessage.Attributes.Add("class", "error-msg");
                        return;
                    }
                }
                else
                {
                    user.ProfilePictureURL = applicationUser.ProfilePictureURL;
                }


                success = manager.UpdateUser(user);

                if (success)
                {

                    this.pageActionMessage.InnerText = "Your information was successfully added to the system. Try login to the system.";
                    this.pageActionMessage.Attributes.Add("class", "success-msg");
                }
                else
                {
                    this.pageActionMessage.InnerText = "Failed to add your information to the system";
                    this.pageActionMessage.Attributes.Add("class", "error-msg");
                }
            }
            catch (Exception eX)
            {
                this.pageActionMessage.InnerText = "Failed to update your information to the system";
                this.pageActionMessage.Attributes.Add("class", "error-msg");
            }
            finally
            {
                manager = null;
                user = null;
            }
        } 
        #endregion
    }
}